# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(dplyr)
library(tidyr)
library(tibble)
library(scatterplot3d)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

classNotes <- sampleInfo %>%
.$ClassNote %>%
unique()

sampleColDf <- read.table(opt$sc, header = T, sep = "\t", stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))

cn <- combn(classNotes, 2)
for (i in 1 : ncol(cn)) {
    row <- cn[, i]
    group1Name <- row[1]
    group2Name <- row[2]
    parent <- paste0(group2Name, "_", group1Name)
    createWhenNoExist(parent)
    pcDataFileName <- paste0(parent, "/PCA_", group2Name, "_", group1Name , "_data.txt")

    pc123 <- read.table(pcDataFileName, header = T, sep = "\t", stringsAsFactors = F, comment.char = "") %>%
        as.data.frame() %>%
        select(c("SampleID", "p1", "p2", "p3")) %>%
        left_join(sampleInfo, by = c("SampleID")) %>%
        left_join(sampleColDf, by = c("ClassNote"))

    fileName <- paste0(parent, "/PCA_", group2Name, "_", group1Name, "_3D.pdf")
    pdf(fileName, width = 8, height = 8)

    parameterFileName <- paste0(parent, "/PCA_", group2Name, "_", group1Name , "_Parameters.csv")
    parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

    impoPc1 <- parameterData[1, "PC1"]
    impoPc1 <- round(impoPc1 * 100, 2)
    impoPc2 <- parameterData[1, "PC2"]
    impoPc2 <- round(impoPc2 * 100, 2)
    impoPc3 <- parameterData[1, "PC3"]
    impoPc3 <- round(impoPc3 * 100, 2)

    opar <- par(no.readonly = TRUE)
    par(family = "Times")

    scatterplot3d(pc123$p1, pc123$p2, pc123$p3, color = pc123$col, main = "", pch = 20, col.axis = "grey",
    mar = c(5, 3, 1, 3) + 0.1, cex.symbols = 6, xlab = paste0("PC1(", impoPc1, "%)"), ylab = paste0("PC2(", impoPc2, "%)"),
    zlab = paste0("PC3(", impoPc3, "%)"), angle = 60, cex.lab = 2, cex.axis = 1.5)
    par(opar)

    dev.off()
}



